package com.qiuzhao.utils;

import com.alibaba.nls.client.AccessToken;
import com.alibaba.nls.client.protocol.NlsClient;
import com.alibaba.nls.client.protocol.OutputFormatEnum;
import com.alibaba.nls.client.protocol.SampleRateEnum;
import com.alibaba.nls.client.protocol.tts.SpeechSynthesizer;
import com.alibaba.nls.client.protocol.tts.SpeechSynthesizerListener;
import com.alibaba.nls.client.protocol.tts.SpeechSynthesizerResponse;
import com.qiuzhao.entity.Role;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * 阿里云 TTS 工具类：传入文本，返回语音二进制数据
 */
public class AliyunTtsUtil {

    private static final Logger log = LoggerFactory.getLogger(AliyunTtsUtil.class);

    private final String appKey;
    private final String accessKeyId;
    private final String accessKeySecret;
    private final String url;
    private final Role role;

    public AliyunTtsUtil(String appKey, String accessKeyId, String accessKeySecret, String url, Role role) {
        this.appKey = appKey;
        this.accessKeyId = accessKeyId;
        this.accessKeySecret = accessKeySecret;
        this.url = url;
        this.role = role;
    }

    /**
     * 文本转语音
     * @param text 要合成的文本
     * @return byte[] 音频数据 (WAV/PCM/MP3)
     */
    public byte[] synthesize(String text) throws Exception {
        AccessToken accessToken = new AccessToken(accessKeyId, accessKeySecret);
        accessToken.apply();

        NlsClient client = url == null || url.isEmpty()
                ? new NlsClient(accessToken.getToken())
                : new NlsClient(url, accessToken.getToken());

        ByteArrayOutputStream out = new ByteArrayOutputStream();

        SpeechSynthesizerListener listener = new SpeechSynthesizerListener() {
            @Override
            public void onMessage(ByteBuffer message) {
                try {
                    byte[] buffer = new byte[message.remaining()];
                    message.get(buffer);
                    out.write(buffer);
                } catch (IOException e) {
                    log.error("[TTS Write Error]", e);
                }
            }

            @Override
            public void onComplete(SpeechSynthesizerResponse response) {
                log.info("[TTS Complete] name={}, status={}", response.getName(), response.getStatus());
            }

            @Override
            public void onFail(SpeechSynthesizerResponse response) {
                log.error("[TTS Fail] taskId={}, status={}, msg={}",
                        response.getTaskId(), response.getStatus(), response.getStatusText());
            }
        };

        SpeechSynthesizer synthesizer = new SpeechSynthesizer(client, listener);
        synthesizer.setAppKey(appKey);
        synthesizer.setFormat(OutputFormatEnum.MP3);  // 你也可以改成 WAV/PCM
        synthesizer.setSampleRate(SampleRateEnum.SAMPLE_RATE_16K);
        synthesizer.setVoice(role.getVoice());   // 发音人，可换成 "xiaoyun" "xiaogang"
        synthesizer.setSpeechRate(0);    // 语速（-500~500）
        synthesizer.setPitchRate(0);     // 音调（-500~500）
        synthesizer.setVolume(100);
        synthesizer.setText(text);

        synthesizer.start();
        synthesizer.waitForComplete();
        synthesizer.close();

        client.shutdown();

        return out.toByteArray();
    }
}
